package cn.newgrand.netcall.integration.menu;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.jivesoftware.Spark;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.SharedGroupManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.Workspace;
import org.jivesoftware.spark.component.VerticalFlowLayout;
import org.jivesoftware.spark.plugin.ContextMenuListener;
import org.jivesoftware.spark.ui.ContactGroup;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;

import cn.newgrand.netcall.integration.AppSysRes;
import cn.newgrand.netcall.integration.IntegrationManager;

/**
 * @author SidneyRen E-mail:SidneyRen@hotmail.com
 * @version create time：2010-11-4 下午08:03:29
 * 类说明
 */
public class AppSysPanel extends JPanel{
	private static final long                  serialVersionUID  = 1L;

    private JPanel                             mainPanel         = new JPanel();
    private JScrollPane                        menuListScrollPane;
    
    private AppSysMenuHandler menuHandler = IntegrationManager.getAppSysMenuHandler();
    private final List<AppSysItemGroup> groupList     = new ArrayList<AppSysItemGroup>();
    private final Map<String,AppSysItemGroup> groupMap = new HashMap<String, AppSysItemGroup>();

//    private final List<AppSysItemGroup> groupList         = new ArrayList<AppSysItemGroup>();

//    private MenuManager                        menuManager;

    public static KeyEvent                     activeKeyEvent;

    private final List<ContextMenuListener>    contextListeners  = new ArrayList<ContextMenuListener>();
    private AppSysItemGroup funcMenuGroup = new AppSysItemGroup("快捷功能菜单");
    private Collection<AppSysItem> funcMenuList = new ArrayList<AppSysItem>();
    private AppSysItem noFuncMenuItem = new AppSysItem(null,"没有快捷功能菜单",null,null);
    
    
//    private final List<MenuListListener>       menuListListeners = new ArrayList<MenuListListener>();

//    public AppSysPanel(MenuManager menuManager)
    public AppSysPanel()
    {
        setLayout(new BorderLayout());
        
        
        mainPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false));
        mainPanel.setBackground((Color) UIManager.get("ContactItem.background"));
        
        menuListScrollPane = new JScrollPane(mainPanel);
        menuListScrollPane.setAutoscrolls(true);
        menuListScrollPane.setBorder(BorderFactory.createEmptyBorder());
        menuListScrollPane.getVerticalScrollBar().setBlockIncrement(50);
        menuListScrollPane.getVerticalScrollBar().setUnitIncrement(20);

        add(menuListScrollPane, BorderLayout.CENTER);

//        this.menuManager = menuManager;
    }

    public void initialize()
    {
    	setBorder(BorderFactory.createEmptyBorder());
    	// Add Menu List
    	addAppSysToWorkspace();
    	
        buildInitAppSysPanel();
        
        // Hide top toolbar
//        SparkManager.getMainWindow().getTopToolBar().setVisible(false);

        final Runnable sharedGroupLoader = new Runnable() {
            public void run() {
                // Retrieve shared group list.
//                try {
//                    sharedGroups = SharedGroupManager.getSharedGroups(SparkManager.getConnection());
//                }
//                catch (XMPPException e) {
//                    Log.error("Unable to contact shared group info.", e);
//                }
            	
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
//                    	 buildMenuList();
                    }
                });

            }
        };

        TaskEngine.getInstance().submit(sharedGroupLoader);
       
    }
    
    private void buildInitAppSysPanel(){
    	addAppSysItemGroup(funcMenuGroup);
        funcMenuGroup.setVisible(true);
    }

    private void addAppSysToWorkspace()
    {
        Workspace workspace = SparkManager.getWorkspace();
        LocalPreferences preferences = SettingsManager.getLocalPreferences();
        if(!preferences.isPublicLogin()){
        	workspace.getWorkspacePane().addTab("工作管理", AppSysRes.getImageIcon(AppSysRes.INTEGRATION_IMAGE), this); // NOTRANS
        }
    }

    public void buildMenuList()
    {
    	IntegrationManager.getAppSysMenuHandler().loadMenu();
    	funcMenuList = menuHandler.getFuncMenuList();
    	if(funcMenuList.size()!=0){
	    	for (AppSysItem item : funcMenuList) {
	    		funcMenuGroup.addAppSysItem(item);
			}
    	}else{
    		//TODO 添加没有快捷功能菜单的时候显示的item
    		funcMenuGroup.addAppSysItem(noFuncMenuItem);
		}
    	

//    	
//    	Map<String,AppSysItemGroup> tempGroup = IntegrationManager.getAppSysMenuHandler().getAppSysItemGroup();
//    	groupMap.putAll(IntegrationManager.getAppSysMenuHandler().getAppSysItemGroup());
//    	
//    	for (AppSysItemGroup group : groupMap.values()) {
//    		addAppSysItemGroup(group);
//    		group.setVisible(true);
//		}
    	
    }
    /**
     * Adds a new ContactGroup to the ContactList.
     *
     * @param group the group to add.
     */
    private void addAppSysItemGroup(AppSysItemGroup group) {
        groupList.add(group);

        Collections.sort(groupList, GROUP_COMPARATOR);

        try {
            mainPanel.add(group, groupList.indexOf(group));
        }
        catch (Exception e) {
            Log.error(e);
        }

//        group.addContactGroupListener(this);

//        fireContactGroupAdded(group);
//
//        // Check state
//        String prop = props.getProperty(group.getGroupName());
//        if (prop != null) {
//            boolean isCollapsed = Boolean.valueOf(prop);
//            group.setCollapsed(isCollapsed);
//        }
    }
    
    /**
     * Sorts ContactGroups
     */
    public static final Comparator<AppSysItemGroup> GROUP_COMPARATOR = new Comparator<AppSysItemGroup>() {
        public int compare(AppSysItemGroup group1, AppSysItemGroup group2) {
            // Make sure that offline group is always on bottom.
            if (group2.isOfflineGroup()) {
                return -1;
            }

            return group1.getGroupName().trim().toLowerCase().compareTo(group2.getGroupName().trim().toLowerCase());
        }
    };
}

    
